package net.xfok.preference;

import java.util.Iterator;
import java.util.Map;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.util.Log;

public class MyPreference extends PreferenceActivity implements OnSharedPreferenceChangeListener  {
	
	private static final String TAG="MyPreference";

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);  
        SharedPreferences sp=getPreferenceScreen().getSharedPreferences();
        sp.registerOnSharedPreferenceChangeListener(this);
        String v= sp.getString("test", "default");
        PreferenceCategory pc=new PreferenceCategory(this);
        pc.setTitle("test");
        EditTextPreference et=new EditTextPreference(this);
        et.setTitle("this is a test");
        et.setKey("test");
        et.setSummary(v);
        PreferenceScreen pres=getPreferenceManager().createPreferenceScreen(this);
        pres.setTitle("test");
        getPreferenceScreen().addPreference(pc);
        pres.addPreference(et);
        getPreferenceScreen().addPreference(pres);
        setValues(sp);
	}
	
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
		// TODO Auto-generated method stub
		Log.i(TAG, "key="+key);			
		setSummary(key, sharedPreferences);
	}
	
	private void setValues(SharedPreferences sharedPreferences){
		Map map=sharedPreferences.getAll();
		Iterator it=map.keySet().iterator();
		while(it.hasNext()){
			String key=it.next().toString();
			Log.i(TAG,"key="+key);
			setSummary(key, sharedPreferences);
		}
	}
	
	private void setSummary(String key,SharedPreferences sharedPreferences){
		
		Preference preference=(Preference)findPreference(key);
		if(preference instanceof CheckBoxPreference){
			Log.i(TAG, "This is a CheckBox");
		}else if(preference instanceof EditTextPreference){
			String value=sharedPreferences.getString(key,"");
			Log.i(TAG, "value="+value);
			preference.setSummary(value);	
		}else if(preference instanceof ListPreference){
			String value=sharedPreferences.getString(key,"");
			Log.i(TAG, "value="+value);
			preference.setSummary(key+":"+value);	
		}
	}

   
}